package cn.lrwjz.geotest.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.lrwjz.geotest.MyApplication;


public class SpUtils {
    private static final String SP_NAME = "geotest_config";
    private static SpUtils instance;
    private static Context appContext;
    private SharedPreferences sp;

    private SpUtils(Context context) {
        if (context != null) {
            sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
    }

    public static void init(Context context) {
        if (appContext == null && context != null) {
            appContext = context.getApplicationContext();
            instance = new SpUtils(appContext);
        }
    }

    public static SpUtils obtain() {
        if (instance == null) {
            synchronized (SpUtils.class) {
                if (instance == null) {
                    if (appContext != null) {
                        instance = new SpUtils(appContext);
                    } else {
                        throw new IllegalStateException("SpUtils not initialized! Call init() first.");
                    }
                }
            }
        }
        return instance;
    }

    public void putString(String key, String value) {
        if (sp != null) {
            sp.edit().putString(key, value).apply();
        }
    }

    public String getString(String key) {
        return sp != null ? sp.getString(key, null) : null;
    }

    public void putBoolean(String key, boolean value) {
        if (sp != null) {
            sp.edit().putBoolean(key, value).apply();
        }
    }

    public boolean getBoolean(String key, boolean defaultValue) {
        return sp != null ? sp.getBoolean(key, defaultValue) : defaultValue;
    }

    public void putInt(String key, int value) {
        if (sp != null) {
            sp.edit().putInt(key, value).apply();
        }
    }

    public int getInt(String key, int defaultValue) {
        return sp != null ? sp.getInt(key, defaultValue) : defaultValue;
    }

    public void putLong(String key, long value) {
        if (sp != null) {
            sp.edit().putLong(key, value).apply();
        }
    }

    public long getLong(String key, long defaultValue) {
        return sp != null ? sp.getLong(key, defaultValue) : defaultValue;
    }

    public void remove(String key) {
        if (sp != null) {
            sp.edit().remove(key).apply();
        }
    }

    public void clear() {
        if (sp != null) {
            sp.edit().clear().apply();
        }
    }
}
